<template>
  <view class="indexWraps">
    <view v-for="(item, index) in state.healthListNew" :key="index" class="card">
      <view
        v-if="
          item.typeCheck != 'water' &&
          item.typeCheck != 'blood_fat' &&
          item.typeCheck != 'liver_function' &&
          item.typeCheck != 'defecate'
        "
      >
        <!-- <view class="title" v-if="index"> -->
        <view class="title">
          <view>{{ item.date }}</view>
          <view class="source">
            <text> 来源： </text>
            <text> {{ item.dataSource }} </text>
          </view>
        </view>
        <up-swipe-action ref="swipeRef" autoClose>
          <!-- <up-swipe-action-item :options="options" @click="handleClick(item1, index1, item, index)"> -->
          <up-swipe-action-item :options="options" @click="handleClick(item, index)">
            <view class="item" @tap="edit(state.type, item)">
            <!-- <view class="item"> -->
              <view class="top">
                <text class="name">{{ item.name }} </text>
                <text class="postprandial" v-if="item.typeCheck == 'fbg'"
                  >{{ item.fbg ? '空腹' : '餐后' }}
                </text>
                <text
                  class="postprandial"
                  v-if="item.typeCheck == 'blood_sugar' && item.details[0].indicatorName"
                >
                  {{ item.details[0].indicatorName }}
                </text>
                <!-- status red    yellow  orange  green -->
                <text :class="['status', item.color ? item.color : '']" v-if="item.normalFlagName">
                  {{ item.normalFlagName }}
                </text>
                <text class="time" v-if="item.typeCheck != 'sleep'"> {{ item.timeMin }}</text>
              </view>
              <view class="min">
                <view class="name" v-if="item.typeCheck == 'bmi'">
                  <view class="weight">体重</view>
                  <view class="unitWrap">
                    <text class="num"> {{ item.weight }}</text>
                    <text class="unit">kg</text>
                  </view>
                </view>
                <view class="name" v-if="item.typeCheck == 'bmi'">
                  <view class="weight">{{ item.name }}</view>
                  <view class="unitWrap">
                    <text class="num"> {{ item.num }}</text>
                    <text class="unit">kg/㎡</text>
                  </view>
                </view>
                <view class="name" v-else-if="item.typeCheck == 'whr'">
                  <text class="whrNum"> {{ item.num }}</text>
                </view>
                <view
                  class="name"
                  style="justify-content: flex-start"
                  v-else-if="
                    item.typeCheck == 'sbp' ||
                    item.typeCheck == 'heart_rate' ||
                    item.typeCheck == 'blood_sugar' ||
                    item.typeCheck == 'spo2' ||
                    item.typeCheck == 'blood_ketone' ||
                    item.typeCheck == 'uric_acid'
                  "
                >
                  <view class="sbp" v-if="item.typeCheck == 'sbp'">
                    <text class="num"> {{ item.sbp }}/{{ item.dbp }}</text>
                    <text class="unit">mmHg</text>
                  </view>
                  <view class="sbp" style="margin-left: 32rpx" v-if="item.typeCheck == 'sbp'">
                    <text class="num">{{ item.pulseRate }}</text>
                    <text class="unit">bpm</text>
                  </view>
                  <view class="sbp" v-else-if="item.typeCheck == 'heart_rate'">
                    <text class="num"> {{ item.heartRate }}</text>
                    <text class="unit">次/分</text>
                  </view>
                  <view
                    class="sbp"
                    v-else-if="
                      item.typeCheck == 'blood_sugar' ||
                      item.typeCheck == 'blood_ketone' ||
                      item.typeCheck == 'uric_acid'
                    "
                  >
                    <text class="num"> {{ item.details[0].indicatorValue }}</text>
                    <text class="unit">{{ item.unit }}</text>
                  </view>
                  <view class="sbp" v-else-if="item.typeCheck == 'spo2'">
                    <text class="num"> {{ item.spo2 }}</text>
                    <text class="unit">%</text>
                  </view>
                </view>
                <view class="name sleepName" v-if="item.typeCheck == 'sleep'">
                  <text class="num">睡眠时长</text>
                  <text class="unit">{{ item.timeMin }}</text>
                </view>
                <view class="name sleepName" v-if="item.typeCheck == 'sleep'">
                  <text class="num"> 入睡时间</text>
                  <text class="unit">{{ item.timeMinGo }}</text>
                </view>
              </view>

              <!-- 备注 暂时没有显示 -->
              <view class="bottom" v-if="item.remark">
                <text class="remark">备注：</text>
                <text class="remarkContent">
                  {{ item.remark }}
                </text>
              </view>
            </view>
            <!-- 图片展示 -->
            <view v-if="isSign" class="picList">
              <image
                v-for="(picItem, picIndex) of item.campWieghtPics"
                :key="picIndex"
                @tap="previewImage(picItem.url, item)"
                class="img-bmi"
                :src="picItem.url"
              />
            </view>
          </up-swipe-action-item>
        </up-swipe-action>
      </view>
      <view v-if="item.typeCheck == 'water'">
        <view class="title">
          <view>{{ item.date }}</view>
        </view>
        <view class="title">
          <view class="total-drink">
            <text class="drink-name">当日饮水总量</text>
            <text :class="['status', item.color ? item.color : '']" v-if="item.normalFlagName">
              {{ item.normalFlagName }}
            </text>
          </view>
          <view class="drink">
            <text class="drink-name">{{ item.paramValue }} </text>
            <text style="color: #999; font-size: 24rpx; font-weight: 400">ml</text>
          </view>
        </view>
        <view class="drink-item">
          <up-swipe-action ref="swipeRef" autoClose>
            <up-swipe-action-item
              v-for="(item1, index1) of item.drinkList"
              :key="index1"
              :options="options"
              @click="handleClick(item1, index1, item, index)"
              class="upSwipeActionItem"
            >
              <view class="min-water" @tap="edit(state.type, item1)">
                <view class="num" style="font-size: 28rpx; font-weight: 400; color: #222"
                  >饮水</view
                >
                <view class="value">
                  {{ item1.paramValue }}
                  <text class="unit">ml</text>
                  <image
                    class="img_more"
                    src="https://ainengli.meilianshuke.com/jkhx/common/more.png"
                  />
                </view>
              </view>
            </up-swipe-action-item>
          </up-swipe-action>
        </view>
      </view>
      <view v-if="item.typeCheck == 'blood_fat' || item.typeCheck == 'liver_function'">
        <view class="title">
          <view>{{ item.date }}</view>
          <view class="source">
            <text class="ource_name"> 来源： </text>
            <text class="ource_type"> {{ item.dataSource }} </text>
          </view>
        </view>
        <up-swipe-action ref="swipeRef" autoClose>
          <up-swipe-action-item :options="options" @click="handleClick(item, index)">
            <view class="item" @tap="edit(state.type, item)">
              <view class="top">
                <text class="name">
                  {{ item.name }}
                </text>
                <text class="time"> {{ item.timeMin }}</text>
              </view>
              <view
                class="min"
                style="margin-top: 16rpx"
                v-for="(item1, index1) in item.details"
                :key="index1"
              >
                <view class="name">
                  <text class="label"> {{ typeNewFun(item1.indicatorKey) }}</text>

                  <view class="new-labels">
                    <text class="num">{{ item1.indicatorValue }}</text>
                    <text class="unit">{{ matchUnit() }}</text>
                    <text :class="['status', item1.indicatorStatus == 'N' ? 'green' : 'red']">
                      {{ item1.indicatorStatus == 'N' ? '正常' : '异常' }}
                    </text>
                  </view>
                </view>
              </view>
            </view>
          </up-swipe-action-item>
        </up-swipe-action>
      </view>
      <view v-if="item.typeCheck == 'defecate'">
        <view class="title">
          <view>{{ item.date }}</view>
        </view>
        <view class="defecate-item">
          <up-swipe-action ref="swipeRef" autoClose>
            <up-swipe-action-item :key="item.id" :options="options" @click="handleClick(item, index)" :threshold="35">
              <view class="item" @tap="goAnalyze(item.id)">
                <view :class="['line', 'top_line']">
                  <view class="name">
                    排便 <text class="level" :style="{ background: tagStyleMap[item.healthLevel]?.bg, color: tagStyleMap[item.healthLevel]?.color }">{{ item.healthLevel }}</text>
                  </view>
                  <text class="time">{{ item.timeMin }}</text>
                </view>
                <view class="line">
                  <text class="score_name">
                    排便分数
                  </text>
                  <text class="score"><text class="score_num">{{ item.totalScore }}</text>分</text>
                </view>
              </view>
            </up-swipe-action-item>
          </up-swipe-action>
        </view>
      </view>
    </view>
    <view class="loading">
      <my-loadmore @reload="reload" :status="state.loadstatus" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, watch, ref } from 'vue'
import { parseTime, throttle } from '@/utils/tools'
import MyLoadmore from '../../../../components/MyLoadmore/MyLoadmore.vue'
const props = defineProps({
  message: Object,
  isSign: Boolean,
  type: String
})
const emit = defineEmits(['childEvent', 'reload', 'deleteItem', 'onUpdate'])
const state = reactive({
  healthList: {},
  healthListNew: [],
  type: '',
  loadstatus: ''
})
const options = reactive([
  {
    text: '删除',
    style: {
      backgroundColor: '#ff503d'
    }
  }
])
const swipeRef = ref()
const deleteIndex = ref(0)
const updateId = ref('')
const getSleepTimes = (value: string) => {
  const sleepTimes = value.split('.')
  const hour = Number(sleepTimes[0])
  if (sleepTimes[1]) {
    const minute = Math.round(Number('0.' + sleepTimes[1]) * 60)
    return `${hour}小时${minute > 10 ? minute : '0' + minute}分`
  } else {
    return `${hour}小时`
  }
}
const typeFun = () => {
  switch (state.type) {
    case 'bmi':
      return 'BMI'
    case 'whr':
      return '腰臀比'
    case 'sbp':
      return '血压'
    case 'heart_rate':
      return '心率'
    case 'fbg':
      return '血糖'
    case 'spo2':
      return '血氧'
    default:
      return ''
  }
}
const typeNewFun = (name: string) => {
  switch (name) {
    case 'blood_ketone_data':
      return '血酮'
    case 'uric_acid_data':
      return '尿酸'
    case 'total_cholesterol':
      return '总胆固醇'
    case 'tg':
      return '甘油三酯'
    case 'hdlc':
      return '高密度脂蛋白'
    case 'ldlc':
      return '低密度脂蛋白'
    case 'got':
      return '谷草转氨酶'
    case 'gpt':
      return '谷丙转氨酶'
    case 'ygt':
      return 'Y谷氨酰转肽酶(Y-GT)'
    default:
      return ''
  }
}
const matchUnit = () => {
  switch (state.type) {
    case 'blood_ketone':
      return 'mmol/L'
    case 'uric_acid':
      return 'umol/L'
    case 'blood_fat':
      return 'mmol/L'
    case 'liver_function':
      return 'U/L'
    default:
      return ''
  }
}
watch(
  () => props.message,
  (newValue, oldValue) => {
    console.log(newValue)
    let resultData = newValue.taskList
    state.type = newValue.type
    state.loadstatus = newValue.loadstatus
    let resultDataFilter = []
    for (let i = 0; i < resultData.length; i++) {
      let obj = resultData[i]
      obj.typeCheck = state.type
      if (
        state.type == 'bmi' ||
        state.type == 'whr' ||
        state.type == 'sbp' ||
        state.type == 'heart_rate'
      ) {
        obj.date = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{y}-{m}-{d}')
          : ''
        obj.timeMin = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{h}:{i}')
          : ''
        if (state.type == 'bmi') {
          obj.name = 'BMI'
          obj.num = resultData[i].bmi
        } else if (state.type == 'whr') {
          obj.name = '腰臀比'
          obj.num = resultData[i].whr
        } else if (state.type == 'sbp') {
          obj.name = '血压'
        } else if (state.type == 'heart_rate') {
          obj.name = '心率'
        }
        resultDataFilter.push(obj)
      } else if (
        state.type == 'blood_sugar' ||
        state.type == 'blood_ketone' ||
        state.type == 'uric_acid' ||
        state.type == 'blood_fat' ||
        state.type == 'liver_function'
      ) {
        obj.date = resultData[i].report.checkTime
          ? parseTime(resultData[i].report.checkTime, '{y}-{m}-{d}')
          : ''
        obj.dataSource = resultData[i].report.reportSource ? resultData[i].report.reportSource : ''
        if (state.type == 'blood_sugar') {
          obj.name = '血糖'
        } else if (state.type == 'blood_ketone') {
          obj.name = '血酮'
        } else if (state.type == 'uric_acid') {
          obj.name = '尿酸'
        } else if (state.type == 'blood_fat') {
          obj.name = '血脂'
        } else if (state.type == 'liver_function') {
          obj.name = '肝功能'
        }
        obj.unit = 'mmol/L'
        obj.color = resultData[i].report.color ? resultData[i].report.color : ''
        obj.normalFlagName = resultData[i].report.reportStatusDesc
          ? resultData[i].report.reportStatusDesc
          : ''
        obj.timeMin = resultData[i].report.checkTime
          ? parseTime(resultData[i].report.checkTime, '{h}:{i}')
          : ''
        resultDataFilter.push(obj)
      } else if (state.type == 'spo2') {
        obj.date = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{y}-{m}-{d}')
          : ''
        obj.name = '血氧'
        obj.timeMin = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{h}:{i}')
          : ''
        resultDataFilter.push(obj)
      } else if (state.type == 'sleep') {
        obj.date = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{y}-{m}-{d}')
          : ''
        obj.name = '睡眠'
        obj.timeMin = resultData[i].paramValue.sleepDuration
          ? getSleepTimes(resultData[i].paramValue.sleepDuration)
          : ''
        obj.timeMinGo = resultData[i].paramValue.sleepTime
          ? parseTime(resultData[i].paramValue.sleepTime, '{m}月{d}日 {h}:{i}')
          : ''
        resultDataFilter.push(obj)
      } else if (state.type == 'water') {
        obj.date = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{y}-{m}-{d}')
          : ''
        obj.name = '睡眠'
        obj.timeMin = resultData[i].paramValue.sleepDuration
          ? getSleepTimes(resultData[i].paramValue.sleepDuration)
          : ''
        obj.timeMinGo = resultData[i].paramValue.sleepTime
          ? parseTime(resultData[i].paramValue.sleepTime, '{m}月{d}日 {h}:{i}')
          : ''
        resultDataFilter.push(obj)
      } else if (state.type === 'defecate') {
        obj.date = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{y}-{m}-{d}')
          : ''
        obj.name = '排便'
        obj.timeMin = resultData[i].collectTime
          ? parseTime(resultData[i].collectTime, '{h}:{i}')
          : ''
        resultDataFilter.push(obj)
      }
    }
    state.healthListNew = resultDataFilter
  },
  {
    immediate: true,
    deep: true
  }
)
const edit = (name: 'string', item: any) => {
  if (
    (item && 
    (item.dataSource == '华为运动健康' || 
    item.dataSource == '问卷录入' || 
    item.dataSource == '健康档案')) ||
    (item.report && 
      (item.report.reportSource == '华为运动健康' || 
      item.report.reportSource == '问卷录入' || 
      item.report.reportSource == '健康档案'))
  ) {
    uni.showToast({
      title: '该来源数据不支持编辑!',
      icon: 'none'
    })
    return
  }
  emit('onUpdate', name, 'edit', item)
}
const handleClick = (item: any, index: number, totalItem: any, totalIndex: any) => {
  console.log('删除id', item)
  if (state.type == 'bmi') {
    uni.showToast({
      title: '不能删除体重数据!',
      icon: 'none'
    })
    return
  }
  if (
    (item && item.dataSource == '华为运动健康') ||
    (item.report && item.report.reportSource == '华为运动健康')
  ) {
    uni.showToast({
      title: '不能删除华为同步数据!',
      icon: 'none'
    })
    if (
      state.type == 'water'
    ) {
      let delIndex = 0
      for (let i = 0; i < totalIndex; i++) {
        if (state.type == 'water') {
          delIndex += state.healthListNew[i].drinkList.length
        } else {
          delIndex += state.healthListNew[i].list.length
        }
      }
      swipeRef.value[delIndex + index].closeAll()
      deleteIndex.value = delIndex + index
    } else {
      swipeRef.value[index].closeAll()
      deleteIndex.value = index
    }
    return
  }
  emit('deleteItem', item)
}
const reload = () => {
  emit('reload')
}

const goAnalyze = (id: string) => {
  uni.showLoading({
    title: '加载中...'
  })
  uni.navigateTo({
    url: '/module/src/pages/healthPortrait/defecateAnalyze?id=' + id
  })
}
const tagStyleMap = {
  非常理想: {
    bg: 'rgba(12, 182, 124, 0.10)',
    color: '#0CB67C'
  },
  基本正常: {
    bg: 'rgba(92, 142, 255, 0.10)',
    color: '#5C8EFF'
  },
  轻度异常: {
    bg: 'rgba(255, 129, 60, 0.10)',
    color: '#FF813C'
  },
  明显异常: {
    bg: 'rgba(255, 80, 61, 0.10)',
    color: '#FF503D'
  }
}
const previewImage = (url: any, item: any) => {
  let arr = item.campWieghtPics.map((val) => {
    return val.picBaseUrl + val.picUrl
  })
  uni.previewImage({
    current: url,
    urls: arr
  })
}
</script>

<style lang="scss" scoped>
.indexWraps {
  height: auto;
  .card {
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 0 8rpx;
      font-size: 30rpx;
      color: #222;
      .source {
        font-size: 26rpx;
        color: #999;
      }
    }
    .status {
      display: inline-block;
      padding: 2rpx 20rpx;
      margin-left: 20rpx;
      font-size: 24rpx;
      font-weight: 700;
      vertical-align: middle;
      border-radius: 4rpx;

      &.red {
        color: #ff503d;
        background: rgb(255 80 61 / 10%);
      }

      &.yellow {
        color: #ffd666;
        background: rgb(255 214 102 / 10%);
      }

      &.orange {
        color: #ff813c;
        background: rgb(255 129 60 / 10%);
      }

      &.green {
        color: #0cb67c;
        background: rgb(12 182 124 / 10%);
      }
    }

    .item {
      padding: 32rpx;
      font-size: 32rpx;
      color: #999;
      background: #fff;
      border-radius: 12rpx;

      &:nth-of-type(2) {
        margin-top: 0rpx;
      }

      .top {
        position: relative;
        display: flex;
        align-items: center;

        .name {
          display: inline-block;
          font-weight: 700;
          color: #222;
          vertical-align: middle;
        }

        .postprandial {
          display: inline-block;
          padding: 4rpx 20rpx;
          margin-left: 20rpx;
          font-size: 24rpx;
          color: #666;
          vertical-align: middle;
          background: #f5f5f5;
          border-radius: 20rpx 4rpx;
        }

        .time {
          position: absolute;
          top: 50%;
          right: 0;
          font-size: 14px;
          transform: translateY(-50%);
        }
      }

      .min {
        position: relative;
        min-height: 40rpx;
        margin-top: 32rpx;

        .name {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .weight {
            font-size: 28rpx;
            font-weight: 400;
            color: #222;
          }
          .unitWrap {
            .num {
              display: inline-block;
              font-size: 32rpx;
              font-weight: 700;
              color: #333;
              vertical-align: middle;
            }

            .unit {
              display: inline-block;
              margin-left: 20rpx;
              font-size: 28rpx;
              vertical-align: middle;
            }
          }
          .whrNum {
            display: inline-block;
            font-size: 40rpx;
            font-weight: 700;
            color: #333;
            vertical-align: middle;
          }
          .sbp {
            .num {
              display: inline-block;
              font-size: 40rpx;
              font-weight: 700;
              color: #333;
              vertical-align: middle;
            }
            .unit {
              display: inline-block;
              margin-left: 20rpx;
              font-size: 28rpx;
              vertical-align: middle;
            }
          }
          &.sleepName {
            margin-bottom: 16rpx;
            .num {
              font-size: 28rpx;
              font-weight: 400;
              color: #222;
            }
            .unit {
              font-size: 32rpx;
              font-weight: 600;
              color: #222;
            }
          }
          .new-labels {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            .num {
              display: inline-block;
              font-size: 40rpx;
              font-weight: 700;
              color: #333;
              vertical-align: middle;
            }
            .unit {
              display: inline-block;
              margin-left: 20rpx;
              font-size: 28rpx;
              vertical-align: middle;
            }
          }

          .label {
            font-size: 28rpx;
            font-weight: 400;
            color: #222;
          }
        }

        .remark {
          position: absolute;
          top: 50%;
          right: 0;
          padding: 6rpx 30rpx;
          font-size: 24rpx;
          color: #00d1b6;
          border: 1px solid #00d1b6;
          border-radius: 24rpx;
          transform: translateY(-50%);
        }
      }

      .bottom {
        .remark {
          display: inline-block;
          vertical-align: top;
        }

        .remarkContent {
          box-sizing: border-box;
          display: inline-block;
          width: calc(100% - 46px);
          font-weight: 400;
          color: #666;
          word-wrap: break-word;
          vertical-align: top;
        }
      }
    }
    .picList {
      padding: 0 32rpx 32rpx;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      gap: 16rpx;
      .img-bmi {
        width: 196rpx;
        height: 196rpx;
      }
    }
    .drink-item {
      margin-top: 20rpx;
      font-size: 32rpx;
      color: #222;
      font-weight: 700;
      background: #fff;
      border-radius: 12rpx;
      .min-water {
        position: relative;
        height: 108rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 0 32rpx;
        border-bottom: 1rpx solid #e5e6eb;

        .unit {
          font-size: 24rpx;
          color: #999;
          font-weight: 400;
        }
        .img_more {
          display: inline-block;
          width: 32rpx;
          height: 32rpx;
          transform: translateY(6rpx);
        }
      }
    }

    .defecate-item {
      border-radius: 32rpx;
      // margin-bottom: 24rpx;
      .line {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #222;
        .name {
          font-weight: 700;
          font-size: 32rpx;
          display: flex;
          align-items: center;
          .level {
            padding: 2rpx 20rpx;
            font-size: 24rpx;
            font-weight: 500;
            color: #0CB67C;
            background: rgba(12, 182, 124, 0.10);
            border-radius: 4rpx;
            margin-left: 20rpx;
          }
        }
        .time {
          font-size: 24rpx;
          color: #999;
        }
        .score_name {
          font-size: 28rpx;
        }
        .score {
          color: #999;
          font-size: 28rpx;
          .score_num {
            font-size: 32rpx;
            font-weight: 700;
            margin-right: 16rpx;
            color: #222;
          }
        }
      }
      .top_line {
        margin-bottom: 24rpx;
      }
    }
  }
}
</style>
